package com.wang.powerframeJ.proxy;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wang.powerframeJ.annotation.Transaction;
import com.wang.powerframeJ.helper.DatabaseHelper;

/**
 * 事物代理
 * @author HeJiawang
 * @date   2017年8月8日
 */
public class TransactionProxy implements Proxy {

	private static final Logger LOGGER = LoggerFactory.getLogger(TransactionProxy.class);
	
	/**
	 * 本地线程池，保证线程安全
	 */
	private static final ThreadLocal<Boolean> FLAG_HOLDER = new ThreadLocal<Boolean>() {

		@Override
		protected Boolean initialValue() {
			return false;
		}
		
	};
	
	@Override
	public Object doProxy(ProxyChain proxyChain) throws Throwable {
		Object result;
		boolean flag = FLAG_HOLDER.get();
		Method method = proxyChain.getTargetMethod();
		if( !flag && method.isAnnotationPresent(Transaction.class) ) {
			
			FLAG_HOLDER.set(true);
			try {
				DatabaseHelper.beginTransaction();
				LOGGER.debug(" begin transaction ");
				
				result = proxyChain.doProxyChain();
				
				DatabaseHelper.commitTransaction();
				LOGGER.debug(" commit transaction ");
			} catch (Exception e) {
				DatabaseHelper.rollbackTransaction();
				LOGGER.debug(" rollback transaction ");
				throw e;
			} finally {
				FLAG_HOLDER.remove();
			}
		} else {
			result = proxyChain.doProxyChain();
		}
		
		return result;
	}
}
